package com.dingding.gmall.order.interceptor;

import com.dingding.gmall.common.constant.AuthServerConstant;
import com.dingding.gmall.common.dto.MemberDTO;
import com.dingding.gmall.order.config.URIConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author liugongding
 * @description:
 * @date 2022/2/24 11:29 PM
 */

@Component
public class LoginInterceptor implements HandlerInterceptor {

      public static ThreadLocal<MemberDTO> memberDTOThreadLocal = new ThreadLocal<>();

      @Autowired
      private URIConfig uriConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        List<String> listProp = uriConfig.getListProp();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String uri : listProp) {
            boolean match = antPathMatcher.match(uri, requestURI);
            if (match) {
                return true;
            }
        }

        Object object = request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (object == null) {
            //未登录
            request.getSession().setAttribute("loginMsg","请先进行登录");
            response.sendRedirect("http://127.0.0.1:9877/login.html");
            return false;
        } else {
            //已登录
            MemberDTO member = (MemberDTO)object;
            memberDTOThreadLocal.set(member);
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
